/**
 * author:Administrator
 * date:2016/1/5
 * desc:TODO
 */
'use strict';

var assert = require('assert');
var request = require('request');

var orderId;
function waitResetDone(done) {
  if (!!orderId)done();
  else setTimeout(function () {
    waitResetDone(done);
  }, 500);
}

describe('repeat post', function () {
  var resetUrl = 'http://localhost:9990/orders/reset';
  it('reset', function (done) {
    request(resetUrl, function (err, res, data) {
      assert.equal(null, err);
      //console.log(data);
      if (typeof data === 'string') data = JSON.parse(data);
      assert.equal(data.errcode, 0);
      orderId = data.order.oid;
      done();
    });
  });
});


describe('repeat post', function () {
  this.timeout(5000);
  before(function (done) {
    waitResetDone(done);
  });

  var reqCnt = 3;

  var msg = 'repeat post=%reqCnt'.replace('%reqCnt', reqCnt);
  it(msg, function (done) {
    var opt = {
      uri: 'http://localhost:9990/orders/payment',
      method: 'POST',
      json: {"orderid": orderId}
    };
    var resCnt = 0, i = 0;
    var failCnt = 0;
    for (i = 0; i < reqCnt; i++) {
      request(opt, function (err, res, data) {
        assert.equal(null, err);
        resCnt++;
        //console.log(data);
        if (typeof data === 'string') data = JSON.parse(data);
        if (data.errcode != 0) {
          failCnt++;
        }
        if (resCnt == reqCnt) {
          assert.equal(failCnt, reqCnt - 1); // only allow one pay success
          done();
        }
      });
    }
  });
});